package com.cyzy.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UpdataImage {

    // 从配置文件获取上传目录
    @Value("${spring.uploads.directory}")
    private String UPLOAD_DIR;

    @PostMapping("/image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }

        try {
            // 文件类型检查
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseEntity.badRequest().body("只允许上传图片文件");
            }

            // 获取文件名并使用UUID生成唯一文件名
            String originalFileName = file.getOriginalFilename();
            Path safePath = Paths.get(originalFileName).normalize();
            String newFileName = UUID.randomUUID().toString() + "_" + safePath.getFileName();

            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path targetPath = uploadPath.resolve(newFileName);
            file.transferTo(targetPath);

            // 返回文件的访问URL
            String fileUrl = "http://localhost:9999/shopping-upload/upload/image/"+ newFileName;
            return ResponseEntity.ok(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("上传失败，请稍后重试");
        }
    }

    @GetMapping("/image/{filename}")
    public ResponseEntity<byte[]> getImage(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR + filename);
            byte[] fileContent = Files.readAllBytes(filePath);

            // 获取文件类型并返回
            String contentType = Files.probeContentType(filePath);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(404).body(null);
        }
    }
}
